package com.adulcimer.services;

import jakarta.annotation.Resource;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.springframework.stereotype.Service;

/**
 * @author Simon
 * @create 2025/2/6
 * @Description
 **/

@Service
public class MyElasticsearchService {

    @Resource
    private RestClient restClient ;

    public void addDocument(String index, String id, String jsonContent) throws Exception {
        Request request = new Request("PUT", "/" + index + "/_doc/" + id);
        request.setEntity(new StringEntity(jsonContent, ContentType.APPLICATION_JSON));
        restClient.performRequest(request);
    }

    public String getDocument(String index, String id) throws Exception {
        Request request = new Request("GET", "/" + index + "/_doc/" + id);
        Response response = restClient.performRequest(request);
        return EntityUtils.toString(response.getEntity());
    }

    public void updateDocument(String index, String id, String jsonContent) throws Exception {
        Request request = new Request("POST", "/" + index + "/_update/" + id);
        StringEntity entity = new StringEntity("{\"doc\":" + jsonContent + "}", ContentType.APPLICATION_JSON);
        request.setEntity(entity);
        restClient.performRequest(request);
    }

    public void deleteDocument(String index, String id) throws Exception {
        Request request = new Request("DELETE", "/" + index + "/_doc/" + id);
        restClient.performRequest(request);
    }
}
